﻿using ELab.Core.Serialization.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ELab.Message
{
    public class FilesSynchMessage
    {
        public FilesSynchMessage()
        {
        }


        public List<string> Users { get; set; }

        public List<SynFileInfor> FileInfors { get; set; }

        public byte[] Data
        {
            get
            {
                var data = new byte[] { 0, 0, 0, 0 };

                var userSentData = Users.XmlSerializeToByte();
               
                //Update length of list user sent
                var bytesLength = BitConverter.GetBytes(userSentData.Length);
                bytesLength.CopyTo(data, 0);

                //add Users sent name
                data = data.Append<byte>(userSentData);

                //add File Infor sent data
                var fileInfosData = FileInfors.XmlSerializeToByte();
                data = data.Append<byte>(fileInfosData);

                return data;
            }
        }

        public static FilesSynchMessage FromData(byte[] data)
        {
            FilesSynchMessage result = null;
            try
            {
                if (data == null || data.Length < 4) return null;

                byte[] lengBytes = new byte[] { data[0], data[1], data[2], data[3] };
                int length = BitConverter.ToInt32(lengBytes, 0);

                if (length <= 0) return null;

                int index = 4; //start Data of the users
                var endIndex = index;


                // Gets a value of path
                endIndex += length;
                var usersBytes = data.Skip(index).Take(endIndex - index).ToArray();
                var users = usersBytes.XmlDeserialize<List<string>>();
                 
                index = endIndex;
                var fileBytes = data.Skip(index).ToArray();
                var fileInfors = fileBytes.XmlDeserialize<List<SynFileInfor>>();
                 
                //result value
                result = new FilesSynchMessage();
                result.FileInfors = fileInfors;
                result.Users = users;
            }
            catch
            {
            }
            return result;
        }
    }
}
